package com.tstudy.laoshibang.base;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.login.LoginActivity;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.profile.UserInfoFragment.UserInfoCallBack;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * Fragment 基类
* @CopyRight weitaming.com
* @author wuyahui
* @E-mail wuyahui@ispied.com
* @version 1.0.0
* @Date 2014年4月29日 下午5:03:44
 */
public abstract class BaseFragment extends Fragment {
	public BaseActivity mBaseActivity;
	public boolean mIsLoading;
	public int mFragmentId;
	public long mMallId;
	private ProgressDialog mProgressDialog;
	public Handler mHandler;
	public int start;
	public int pageSize = 20;
	public int limit = pageSize;
	public int totalCount = 0;
	public Gson mGson;
	private Dialog dialog;
	public BaseFragment() {
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		LogUtil.d("--onActivityCreated::" + this);
		super.onActivityCreated(savedInstanceState);
	}
	@Override
	public void onAttach(Activity activity) {
		LogUtil.d("--onAttach::" + this + ",Activity==" + this.getActivity());
		super.onAttach(activity);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LogUtil.d("--onCreate::" + this);
		mBaseActivity = (BaseActivity) getActivity();
		initArgs(getArguments());
		mGson = new Gson();
		mHandler = new Handler();
	}
	/**
	 * 显示或隐藏首页tab
	 * @param isShow
	 */
	public void showIndexTab(boolean isShow){
//		((IndexActivity)(IspiedApplication.mCurrentActivity)).showTabLayout(isShow);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(savedInstanceState != null){
//			if(((BaseActivity)getActivity()).mTabFragmentId == 0){
				((BaseActivity)getActivity()).mRootFragmentId = savedInstanceState.getInt(CONSTANT.ARGS.TAB_FRAGMENT_ID);
				mFragmentId = savedInstanceState.getInt(CONSTANT.ARGS.FRAGMENT_ID);
//			}
//			if (O2OApplication.mUser == null) {
//				O2OApplication.mUser = (User) savedInstanceState.getSerializable(CONSTANT.ARGS.USER_PROFILE);
//			}
//			if (O2OApplication.mLoginResult == null) {
//				O2OApplication.mLoginResult = (LoginResult) savedInstanceState.getSerializable(CONSTANT.ARGS.LOGIN_RESULT);
//			}
		}
		LogUtil.d("--onCreateView::" + this);
		mIsLoading = false;
		return super.onCreateView(inflater, container, savedInstanceState);
	}
	
	@Override
	public void onStart() {
		LogUtil.d("--onStart::" + this);
		super.onStart();
	}
	@Override
	public void onResume() {
		LogUtil.d("--onResume::" + this.getTag());
		super.onResume();
		MobclickAgent.onPageStart(this.getTag()); //统计页面
	}
	@Override
	public void onPause() {
		LogUtil.d("--onPause::" + getTag());
		super.onPause();
		MobclickAgent.onPageEnd(this.getTag()); 
	}
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		LogUtil.d("-----------execute BaseFragment onSaveInstanceState");
//		outState.putSerializable(CONSTANT.ARGS.USER_PROFILE, O2OApplication.mUser);
//		outState.putSerializable(CONSTANT.ARGS.LOGIN_RESULT, O2OApplication.mLoginResult);
		outState.putInt(CONSTANT.ARGS.TAB_FRAGMENT_ID,((BaseActivity)getActivity()).mRootFragmentId);
		outState.putInt(CONSTANT.ARGS.FRAGMENT_ID,mFragmentId);
		LogUtil.d("--onSaveInstanceState::" + this);
	}
	@Override
	public void onStop() {
		LogUtil.d("--onStop::" + this);
		
		super.onStop();
	}

	@Override
	public void onDetach() {
		LogUtil.d("--onDetach::" + this + "Activity==" + this.getActivity());
		super.onDetach();
	}
	
	public void backAction(int viewId){
//		if(mBaseActivity.mFragmentStack.size() > 0){
			mBaseActivity.remove(viewId,this);
//		}
	}
	
	public void backAction(int viewId,Fragment fragment){
//		if(mBaseActivity.mFragmentStack.size() > 0){
			mBaseActivity.remove(viewId,fragment);
//		}
	}
	
	public void gotoIndex(int viewId){
		while (mBaseActivity.mFragmentStack.size() > 0) {
			backAction(viewId,mBaseActivity.getTopFragment());
		}
	}
	
	
	public void showSoftKeyBoard(EditText editText,boolean isShow){
		InputMethodManager inputManager = (InputMethodManager)BaseApplication.mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		if(isShow){
        	if(editText != null){
            	inputManager.showSoftInputFromInputMethod(editText.getWindowToken(), 0);
            	inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }else{
        	if(editText != null){
            	inputManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
            }
        }
	}
	
	public void showNotifyDialog(int type, String msg, String pMsg, String nMsg, final UserInfoCallBack callBack) {
		LayoutInflater inflater = LayoutInflater.from(getActivity());
		View dialogView = inflater.inflate(R.layout.common_alert_dialog, null);
		if(dialog == null && getActivity() != null) {
			dialog = buildAlertDialog(dialogView,CommonUtil.dip2px(80));
		}
		TextView tvMsg = (TextView) dialogView.findViewById(R.id.common_alert_dialog_content);
		TextView tvConfirm = (TextView) dialogView.findViewById(R.id.common_alert_dialog_confirm);
		TextView tvCancel = (TextView) dialogView.findViewById(R.id.common_alert_dialog_cancel);
		tvMsg.setText(msg);
		if(type == CONSTANT.DIALOG_DOUBLE_CHOICE) {
			tvConfirm.setVisibility(View.VISIBLE);
			tvConfirm.setText(pMsg);
			tvConfirm.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					hideNotifyDialog();
					callBack.userOP();
				}
			});
		}else {
			tvConfirm.setVisibility(View.GONE);
		}
		tvCancel.setText(nMsg);
		tvCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				hideNotifyDialog();
			}
		});
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}
	
	public void hideNotifyDialog() {
		if(dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog.cancel();
			dialog = null;
		}
	}
	
	public ProgressDialog showProgressDialog(String title, String message, int theme) {
        if (mProgressDialog == null && getActivity() != null) {
            if (theme > 0){
            	mProgressDialog = new ProgressDialog(getActivity(), theme);
            }else{
            	mProgressDialog = new ProgressDialog(getActivity());
            }
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            mProgressDialog.setCanceledOnTouchOutside(false);// 不能取消
            mProgressDialog.setIndeterminate(true);// 设置进度条是否不明确
        }

        if (!TextUtils.isEmpty(title))
            mProgressDialog.setTitle(title);
        mProgressDialog.setMessage(message);
        mProgressDialog.show();
        return mProgressDialog;
 }
 
 public void hideLoadingProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
 }
 
 public void showProgressBar(RelativeLayout progressLayout){
    	if (progressLayout != null && progressLayout.getVisibility() == View.GONE) {
    		progressLayout.setVisibility(View.VISIBLE);
		}
    }
    
    public void hideProgressBar(final RelativeLayout progressLayout) {
        if (progressLayout != null && progressLayout.getVisibility() == View.VISIBLE) {
        	mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					progressLayout.setVisibility(View.GONE);
				}
			},10);
        }
    }
    public abstract class BaseJsonHandler<T> extends BaseJsonHttpResponseHandler<T> {
        @Override
        public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, T response) {
            hideLoadingProgressDialog();
            if (CommonUtil.checkUser((BaseResponse)response)) {
            	if (BaseApplication.checkLogin()) {
             		logout();
 				}else{
 					LoginActivity.show();
 				}
			}
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, T errorResponse) {
            hideLoadingProgressDialog();
//            BaseApplication.showToast(rawJsonData);
            BaseApplication.showToast("数据请求异常");
        }

        @Override
        public void onStart() {
            super.onStart();
            LogUtil.d("onStart showloading::" + this);
//            showLoadingProgressDialog();
        }
    }
    
    public void logout(){
		BaseJsonHandler<BaseResponse> response = new BaseJsonHandler<BaseResponse>() {
			@Override
			public void onStart() {
				showProgressDialog("", "注销...", 0);
				super.onStart();
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					((BaseActivity)getActivity()).logout();
				}else {
                    BaseApplication.showToast(response.getErrMsg());
                }
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().bindPush(false, response);
	}
    @Override
    public void onDestroy() {
        super.onDestroy();
        clear();
        hideLoadingProgressDialog();
        mProgressDialog = null;
    }
    
    public abstract class BaseListJsonHandler<T> extends BaseJsonHttpResponseHandler<T> {
        @Override
        public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, T response) {
            LogUtil.d(rawJsonResponse);
            if (CommonUtil.checkUser((BaseResponse)response)) {
            	if (BaseApplication.checkLogin()) {
             		logout();
 				}else{
 					LoginActivity.show();
 				}
			}
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, T errorResponse) {
//        	BaseApplication.showToast(statusCode + throwable.getMessage());
        	BaseApplication.showToast("数据请求异常");
        	
        }

        @Override
        public void onStart() {
            super.onStart();
            LogUtil.d("onStart showloading::" + this);
        }
    }
    
    public Dialog buildAlertDialog(View dialogView,int margin){
    	Dialog alertDialog;
    	alertDialog = new Dialog(getActivity(),R.style.fullscreendialog);
    		alertDialog.setCanceledOnTouchOutside(true);
    		alertDialog.setContentView(dialogView);
    		Window window = alertDialog.getWindow();
    		window.setBackgroundDrawable(new ColorDrawable(0x00000000));
    		window.setLayout(BaseApplication.mScreenWidth-margin, WindowManager.LayoutParams.WRAP_CONTENT);
    		window.setGravity(Gravity.CENTER);
//    		window.setWindowAnimations(R.style.look_share_show);
    		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
    				| WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    	return alertDialog;
    }

	abstract public void clear();
	abstract public void initArgs(Bundle args);

}